package com.zhucai.credit.service.impl.transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.zhucai.credit.common.CommonEnums.EntType;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.common.MyPage;
import com.zhucai.credit.model.PaymentOrderEntity;
import com.zhucai.credit.model.PaymentOrderItemEntity;
import com.zhucai.credit.model.RefundOrderEntity;
import com.zhucai.credit.repository.PaymentOrderItemRepository;
import com.zhucai.credit.repository.PaymentOrderRepository;
import com.zhucai.credit.repository.RefundOrderRepository;
import com.zhucai.credit.service.cashier.CashierRefundService;
import com.zhucai.credit.to.RefundOrderTO;
import com.zhucai.credit.util.StringUtilsTo;
import com.zhucai.credit.utils.SqlResultUtil;
import com.zhucai.credit.vo.RefundOrderVO;


/**
 * 收银台退款接口实现
 * @author hsg
 *
 */
@Service("cashierRefundService")
@com.alibaba.dubbo.config.annotation.Service(version="1.0.0")
public class CashierRefundServiceImplT implements CashierRefundService {

	private static final Logger logger = LoggerFactory.getLogger(CashierRefundServiceImplT.class);
	@Autowired
	private RefundOrderRepository refundOrderRepository;
	@Autowired
	private PaymentOrderRepository paymentOrderRepository;
	@Autowired
	private PaymentOrderItemRepository paymentOrderItemRepository;

	@Override
	public Page<RefundOrderTO> findRefundOrderRecordList(
			RefundOrderVO refundOrderVO) {
		List<Object[]> objList = new ArrayList<>();
		
	    
		Integer counts = null;
		Calendar calendar = Calendar.getInstance();
 	    SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
	    Date refundApplyStartTime = refundOrderVO.getRefundApplyStartTime();
	    Date refundApplyEndTime = refundOrderVO.getRefundApplyEndTime();
	    try {
			if(refundApplyStartTime !=null){
				String startTimeStr = format.format(refundApplyStartTime);
				refundApplyStartTime = format.parse(startTimeStr);
			}
			if(refundApplyEndTime !=null){
				calendar.setTime(refundApplyEndTime);
				int day = calendar.get(Calendar.DATE);
				calendar.set(Calendar.DATE, day + 1);
				refundApplyEndTime = calendar.getTime();
				String endTimeStr = format.format(refundApplyEndTime);
				refundApplyEndTime = format.parse(endTimeStr);
			}
		} catch (ParseException e) {
			logger.error("### 查询支付账单信息，日期格式化错误");
		}
	    List<String> refundStatusList = null;
	    if(refundOrderVO.getRefundStatus() != null && refundOrderVO.getRefundStatus().length() >=2) {
	    	refundStatusList = new ArrayList<String>();
	    	String[] strArr = refundOrderVO.getRefundStatus().split(",");
	    	for (String str : strArr) {
				refundStatusList.add(str);
			}
	    }
	    if(StringUtils.isEmpty(refundOrderVO.getRefundStatus())) {
	    	refundStatusList = new ArrayList<String>();
	    	refundStatusList.add("REFUND_AMT");
	    	refundStatusList.add("DEAL_WITH");
	    	refundStatusList.add("REFUND_REJECT");
	    }
		//查询申请退款的记录信息
		objList = refundOrderRepository.findRefundOrderRecordList(
				StringUtilsTo.isEmptyToNull(refundOrderVO.getOrderNo()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayEnterpriseName()),
				refundApplyStartTime,refundApplyEndTime,
				StringUtilsTo.isEmptyToNull(refundOrderVO.getProductName()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayStatus()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayType()),
				refundStatusList,refundOrderVO.getUserList(),
				refundOrderVO.getNextPage()*refundOrderVO.getPageSize(), refundOrderVO.getPageSize());
		//查询申请退款的记录条数
		counts = refundOrderRepository.findRefundOrderRecordCounts(
				StringUtilsTo.isEmptyToNull(refundOrderVO.getOrderNo()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayEnterpriseName()),
				refundApplyStartTime,refundApplyEndTime,
				StringUtilsTo.isEmptyToNull(refundOrderVO.getProductName()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayStatus()),
				StringUtilsTo.isEmptyToNull(refundOrderVO.getPayType()),
				refundStatusList,refundOrderVO.getUserList());
		List<RefundOrderTO> roList = new ArrayList<>();
		//判断是否查询到数据
		if(objList != null && objList.size() > 0){
			for (Object[] obj : objList) {
				//封装数据
				RefundOrderTO to = new RefundOrderTO();
				to.setOrderNo(SqlResultUtil.getSqlResultString(obj[0]));
				to.setFlowNumber(SqlResultUtil.getSqlResultString(obj[1]));
				to.setProductName(SqlResultUtil.getSqlResultString(obj[2]));
				to.setOrderAmt(SqlResultUtil.getSqlResultBigDecimal(obj[3]));
				to.setPayStatus(SqlResultUtil.getSqlResultString(obj[4]));
				to.setRefundApplyAmt(SqlResultUtil.getSqlResultBigDecimal(obj[5]));
				to.setRefundStatus(SqlResultUtil.getSqlResultString(obj[6]));
				to.setRefundApplyTime(SqlResultUtil.getSqlResultDate(obj[7]));
				to.setRefundAmt(SqlResultUtil.getSqlResultBigDecimal(obj[8]));
				to.setId(SqlResultUtil.getSqlResultLong(obj[9]));
				to.setRefundApplyReason(SqlResultUtil.getSqlResultString(obj[10]));
				to.setPayType(SqlResultUtil.getSqlResultString(obj[11]));
				to.setPayEnterpriseName(SqlResultUtil.getSqlResultString(obj[12]));
				to.setRefundEnterpriseName(SqlResultUtil.getSqlResultString(obj[13]));
				to.setRefundTime(SqlResultUtil.getSqlResultDate(obj[14]));
				roList.add(to);
			}
		}
		Page<RefundOrderTO> page = new MyPage<RefundOrderTO>(refundOrderVO.getNextPage(), refundOrderVO.getPageSize(), roList, counts);
		return page;
	}

	@Override
	public void createRefundOrder(Long id, BigDecimal refundApplyAmt,
			String refundApplyReason,Long audioUser,Long userId) {
		logger.info("#### 申请退款开始,itemId={}",id);
		RefundOrderEntity entity = new RefundOrderEntity();
		PaymentOrderItemEntity poie = paymentOrderItemRepository.findOne(id);
		PaymentOrderEntity poe = paymentOrderRepository.findByStatusNotAndOrderNo(HelpConstant.Status.delete, poie.getOrderNo());
		entity.setOrderNo(poie.getOrderNo());
		entity.setOrderId(poie.getTid());
		entity.setCreateRefundUser(audioUser);
		entity.setCreateUser(poie.getCreateUser());
		entity.setFlowNumber(poie.getFlowNumber());
		entity.setRefundApplyAmt(refundApplyAmt);
		entity.setOrderAmt(poe.getOrderAmt());
		entity.setPayStatus(poie.getPayStatus());
		entity.setRefundApplyReason(refundApplyReason);
		entity.setRefundApplyTime(new Date());
		entity.setRefundEnterpriseName(poe.getPayEnterpriseName());
		entity.setRefundStatus("DEAL_WITH");
		entity.setPayType(poie.getPayType());
		entity.setRefundEnterpriseName(poe.getCollectEnterpriseName());
		Integer count = paymentOrderItemRepository.updateTradeStatusById(id);
		if(count != 1){
			logger.info("#### 申请退款异常，更新订单明细返回条数异常,itemId={}",id);
			throw new RuntimeException("申请退款异常");
		}
		logger.info("#### 申请退款成功,订单明细更新成功,itemId={}",id);
		refundOrderRepository.save(entity);
		logger.info("#### 新增退款订单信息成功,RefundOrderEntity={}",entity);
		
		
	}
}

